package com.sum.tea.xinlian

import android.app.TabActivity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.media.AudioManager
import android.media.SoundPool
import android.os.Bundle
import android.os.PowerManager
import android.util.Log
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ListView
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import com.bean.ReaderParams
import com.blankj.utilcode.util.ToastUtils
import com.function.AndroidWakeLock
import com.function.SPconfig
import com.function.ScreenListener
import com.pow.api.cls.RfidPower
import com.sum.tea.R
import com.sum.tea.adapter.MyAdapter
import com.sum.tea.contants.AppConfig
import com.sum.tea.databinding.ActivityMainBinding
import com.sum.tea.xinlian.bean.Constants
import com.sum.tea.xinlian.bean.ReadState
import com.sum.tea.xinlian.manager.MainManager
import com.sum.tea.xinlian.viewmodel.MainViewModel
import com.uhf.api.cls.Reader
import com.uhf.api.cls.Reader.*
import com.utils.RootUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.system.exitProcess

class MainActivity : TabActivity() {

    private lateinit var listView: ListView
    private lateinit var mBinding: ActivityMainBinding
    private lateinit var mViewModel: MainViewModel
    private var lifecycleScope = CoroutineScope(Dispatchers.Main)
    private lateinit var myapp: AppConfig
    private lateinit var soundPool: SoundPool
    private lateinit var androidWakeLock: AndroidWakeLock
    private lateinit var mBroadcastReceiver: MyBroadcastReceiver
    private lateinit var screenListener: ScreenListener
    private lateinit var adapter: MyAdapter
    // RULE 为true时候 可以设置默认平台(RULE when is true,that default one PDA platform)
    private var isRuleNoSelPt = false
    private var pdaType = RfidPower.PDATYPE.NONE
    private lateinit var spinner_qmode: Spinner
    private lateinit var button_read: Button
    private lateinit var button_stop:Button
    private lateinit var button_clear:Button
    private lateinit var button_modeset:Button
    private lateinit var tv_once: TextView
    private lateinit var tv_state: TextView
    private lateinit var tv_tags: TextView
    private lateinit var tv_costt: TextView
    private lateinit var tv_timcost: TextView
    private lateinit var tv_statics: TextView
    private lateinit var tv_module: TextView
    var batt_level: Int = 0
    var batt_scale: Int = 0

    // 权限
    var right_reg: Boolean = true

    // 列名定义
    private val columnNames = arrayOf(
        "Sort", "EPC ID", "Count", "ANT", "Protocol",
        "RSSI", "Frequency", "RFU", "TimeStamp", "Data",
        "TID", "BID"
    )

    inner class MyBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                Constants.BROADCAST_ACTION1 -> handleTagBroadcast(intent)
                Constants.BROADCAST_ACTION2 -> button_read.takeIf { it.isEnabled }
                    ?.performClick()

                Constants.BROADCAST_ACTION3 -> button_stop.takeIf { it.isEnabled }
                    ?.performClick()

                Intent.ACTION_BATTERY_CHANGED -> {
                    batt_level = intent.getIntExtra("level", 0)
                    batt_scale = intent.getIntExtra("scale", 0)
                }
            }
        }

        private fun handleTagBroadcast(intent: Intent) {
            val tagInfo = myapp.Mreader.TAGINFO().apply {
                AntennaID = intent.getByteExtra("ANT", 1)
                CRC = intent.getByteArrayExtra("CRC")
                EmbededData = intent.getByteArrayExtra("EMD")
                EmbededDatalen = intent.getShortExtra("EML", 0)
                EpcId = intent.getByteArrayExtra("EPC")
                Epclen = intent.getShortExtra("EPL", 0)
                Frequency = intent.getIntExtra("FRQ", 0)
                PC = intent.getByteArrayExtra("PC")
                Phase = intent.getIntExtra("PHA", 0)
                ReadCnt = intent.getIntExtra("RDC", 0)
                Res = intent.getByteArrayExtra("RES")
                RSSI = intent.getIntExtra("RSI", 0)
                TimeStamp = intent.getIntExtra("TSP", 0)
            }

//            if (myapp.issound) {
//                soundPool.play(1, 1f, 1f, 0, 0, 1f)
//            }
//
//            val epc = Reader.bytes_Hexstr(tagInfo.EpcId)
//            mViewModel.processReceivedTag(epc, tagInfo, myapp.curnxpu8)
//
//            updateTagDisplay()
//            updateReadTimeDisplay(System.currentTimeMillis() - mViewModel.startTick)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        initializeApp()
        mViewModel = MainViewModel(myapp)
        setupViews()
        setupListeners()
        setupScreenListener()
        setupTabHostListener()
        handleDefaultPlatform()
        observeViewModel()
    }

    private fun initializeApp() {
        MainManager.setLange(this)
        RootUtils.runRootCommand("chmod 777 $packageCodePath")
        soundPool = SoundPool(10, AudioManager.STREAM_SYSTEM, 5).apply {
            load(this@MainActivity, R.raw.beep333, 1)
        }
        androidWakeLock = AndroidWakeLock(
            getSystemService(POWER_SERVICE) as PowerManager
        )
        myapp = AppConfig.getInstance().apply {
            Rparams = ReaderParams()
            tabHost = mBinding.tabhost
        }
        registerBroadcastReceiver()
    }

    private fun setupViews() {
        setupTabHost()
        setupButtons()
        setupListView()
        setupSpinner()
        setupHeaderViews()
    }

    private fun setupTabHost() {
        with(mBinding.tabhost) {
            setup()

            if (!isRuleNoSelPt) {
                addTab(
                    newTabSpec("tab1")
                        .setIndicator(
                            AppConfig.Constr_CONNECT,
                            resources.getDrawable(R.drawable.ic_launcher)
                        )
                        .setContent(Intent(this@MainActivity, Sub1TabActivity::class.java))
                )
            }

            addTab(
                newTabSpec("tab2")
                    .setIndicator(AppConfig.Constr_INVENTORY)
                    .setContent(R.id.tab2)
            )

            addTab(
                newTabSpec("tab3")
                    .setIndicator(AppConfig.Constr_RWLOP)
                    .setContent(Intent(this@MainActivity, Sub3TabActivity::class.java))
            )

            addTab(
                newTabSpec("tab4")
                    .setIndicator(AppConfig.Constr_set)
                    .setContent(Intent(this@MainActivity, Sub4TabActivity::class.java))
            )

            // 设置Tab可见性
            val tabWidget = tabHost.tabWidget
            if (!isRuleNoSelPt) {
                tabWidget.getChildAt(1).visibility = View.INVISIBLE
                tabWidget.getChildAt(2).visibility = View.INVISIBLE
                tabWidget.getChildAt(3).visibility = View.INVISIBLE
            }
        }
    }

    private fun setupButtons() {
        button_read = findViewById<View>(R.id.button_start) as Button
        button_stop = findViewById<View>(R.id.button_stop) as Button
        button_stop.setEnabled(false)
        button_clear = findViewById<View>(R.id.button_readclear) as Button
        button_modeset = findViewById<View>(R.id.button_invenmodeset) as Button
        tv_once = findViewById<View>(R.id.textView_readoncecnt) as TextView
        tv_state = findViewById<View>(R.id.textView_invstate) as TextView
        tv_tags = findViewById<View>(R.id.textView_readallcnt) as TextView
        tv_costt = findViewById<View>(R.id.textView_costtime) as TextView
        tv_timcost = findViewById<View>(R.id.textView_costaltime) as TextView
        tv_statics = findViewById<View>(R.id.textView_cavs) as TextView
        tv_module = findViewById<View>(R.id.textView_module) as TextView
        listView = findViewById<View>(R.id.listView_epclist) as ListView
    }

    private fun setupListView() {
        adapter = MyAdapter(
            this,
            mutableListOf(),
            R.layout.listitemview_inv,
            columnNames,
            intArrayOf(R.id.textView_readsort, R.id.textView_readepc,
                R.id.textView_readcnt, R.id.textView_readant,
                R.id.textView_readpro, R.id.textView_readrssi,
                R.id.textView_readfre, R.id.textView_readrfu,
                R.id.textView_readtis, R.id.textView_reademd,
                R.id.textView_readnxpu8_tid, R.id.textView_readnxpu8_bid
            )
        )

        listView.apply {
            this.adapter = this@MainActivity.adapter
            onItemClickListener = AdapterView.OnItemClickListener { _, view, position, _ ->
                handleListItemClick(view, position)
            }
        }
    }

    private fun setupSpinner() {
        spinner_qmode = findViewById<View>(R.id.spinner_invmode) as Spinner
        spinner_qmode.apply {
            adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_spinner_item, AppConfig.spiqmode).apply {
                setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            }

            onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    if (!mViewModel.selectInventoryMode()) {
                        ToastUtils.showShort(AppConfig.Constr_failed)
                    }
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {}
            }
        }
    }

    private fun setupListeners() {
        button_read.setOnClickListener {
            handleStartReading()
        }

        button_stop.setOnClickListener {
            handleStopReading()
        }

        button_clear.setOnClickListener {
            handleClearData()
        }

        button_clear.setOnClickListener {
            handleModeSet()
        }
    }

    private fun handleStartReading() {
        mViewModel.updateConfig(myapp)
        mViewModel.startReading(
            onSound = {
                if (myapp.issound) {
                    soundPool.play(1, 1f, 1f, 0, 0, 1f)
                }
            },
            onUpdateUI = { updateReadState() }
        )
    }

    private fun handleStopReading() {
        mViewModel.stopReading()
    }

    private fun handleClearData() {
        mViewModel.clearData()
        setupHeaderViews()

        if (!myapp.isFoundTag) {
            myapp.Curepc = ""
        }

        if (myapp.issmartmode) {
            myapp.Mreader.Reset_IT()
            if (!button_read.isEnabled) {
                button_stop.performClick()
                button_read.performClick()
            }
        }
    }

    private fun handleListItemClick(view: View, position: Int) {
        // 更新其他项的背景色
        for (i in 0 until listView.count) {
            if (i != position) {
                listView.getChildAt(i)?.let { childView ->
                    (childView.background as? ColorDrawable)?.let { drawable ->
                        if (drawable.color == Color.YELLOW) {
                            childView.setBackgroundColor(
                                if (i % 2 == 0) Color.WHITE else Color.rgb(219, 238, 244)
                            )
                        }
                    }
                }
            }
        }

        // 设置选中项背景色
        view.setBackgroundColor(Color.YELLOW)

        // 处理选中的EPC
        @Suppress("UNCHECKED_CAST")
        val selectedItem = listView.getItemAtPosition(position) as? HashMap<String, String>
        selectedItem?.get("EPC ID")?.let { epc ->
            myapp.Curepc = epc.trim()
            if (myapp.gpodemomode != 0) {
                MainManager.showPopupMenu(
                    applicationContext,
                    view,
                    myapp,
                    mViewModel.gpodemoauthortags
                )
            }
        }
    }

    private fun updateReadState() {
        val tags = mViewModel.tagsMap.value
        tv_tags.text = tags?.size.toString()

        if ((mViewModel.eantCount.value?.size?:0) > 1) {
            val antCounts = mViewModel.eantCount.value?.map { (ant, tags) ->
                "$ant:${tags.size}"
            }?.joinToString(" ")
            tv_tags.text = "${tags?.size} ($antCounts)"
        }
        val timeElapsed = System.currentTimeMillis() - mViewModel.startTick
        tv_timcost.text = "   rt:$timeElapsed"
        adapter.notifyDataSetChanged()
    }

    private fun observeViewModel() {
        lifecycleScope.launch {
            mViewModel.readState.observeForever { state ->
                when (state) {
                    is ReadState.Reading -> {
                        enableReadingState()
                    }

                    is ReadState.Stopped -> {
                        enableStoppedState()
                    }

                    is ReadState.Error -> {
                        handleError(state.error)
                    }
                }
            }
        }

        lifecycleScope.launch {
            mViewModel.errorState.observeForever { error ->
                ToastUtils.showShort(error)
            }
        }
    }

    private fun enableReadingState() {
        button_read.isEnabled = false
        button_stop.isEnabled = true
        val tabWidget = tabHost.tabWidget
        if (isRuleNoSelPt) {
            tabWidget.getChildAt(1).isEnabled = false
            tabWidget.getChildAt(2).isEnabled = false
        } else {
            tabWidget.getChildAt(0).isEnabled = false
            tabWidget.getChildAt(2).isEnabled = false
            tabWidget.getChildAt(3).isEnabled = false
        }
    }

    private fun enableStoppedState() {
        button_read.isEnabled = true
        button_stop.isEnabled = false

        val tabWidget = tabHost.tabWidget
        if (isRuleNoSelPt) {
            tabWidget.getChildAt(1).isEnabled = true
            tabWidget.getChildAt(2).isEnabled = true
        } else {
            tabWidget.getChildAt(0).isEnabled = true
            tabWidget.getChildAt(2).isEnabled = true
            tabWidget.getChildAt(3).isEnabled = true
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (!button_read.isEnabled) {
            Toast.makeText(this, AppConfig.Constr_stopscan, Toast.LENGTH_SHORT).show()
            return true
        }

        when (item.itemId) {
            R.id.action_lasterr -> handleLastError()
            R.id.action_system -> startSystemActivity()
            R.id.action_serial -> startSerialActivity()
            R.id.action_qt -> startQTActivity()
            R.id.action_cw -> startCarrierWaveActivity()
            R.id.action_reg -> startRegisterActivity()
            R.id.action_tagttl -> startTagTempActivity()
            R.id.action_update -> startUpdateActivity()
            else -> return super.onOptionsItemSelected(item)
        }
        return true
    }

    private fun startUpdateActivity() {
        Toast.makeText(this, "请确保已单击连接按钮/Connect", Toast.LENGTH_SHORT).show()
        startActivityForResult(
            Intent(this, UpdateActivity::class.java),
            0
        )
    }

    private fun startSystemActivity() {
        startActivityForResult(
            Intent(this, SubSystemActivity::class.java),
            0
        )
    }

    private fun startSerialActivity() {
        startActivityForResult(
            Intent(this, SubDebugActivity::class.java),
            0
        )
    }

    private fun startQTActivity() {
        if (!checkDeviceConnection()) return
        startActivityForResult(
            Intent(this, SubQTActivity::class.java),
            0
        )
    }

    private fun startCarrierWaveActivity() {
        if (!checkDeviceConnection()) return
        startActivityForResult(
            Intent(this, SubCarryWaveActivity::class.java),
            0
        )
    }

    private fun startRegisterActivity() {
        if (!checkDeviceConnection()) return
        if (!checkRegisterPermission()) return
        startActivityForResult(
            Intent(this, SubRegopActivity::class.java),
            0
        )
    }

    private fun startTagTempActivity() {
        if (!checkDeviceConnection()) return
        startActivityForResult(
            Intent(this, SubTagTempLedActivity::class.java),
            0
        )
    }

    private fun checkDeviceConnection(): Boolean {
        if (!myapp.haveinit) {
            Toast.makeText(this, AppConfig.Constr_connectfialed, Toast.LENGTH_SHORT).show()
            return false
        }
        return true
    }

    private fun checkRegisterPermission(): Boolean {
        if (!right_reg) {
            ToastUtils.showShort("no permissions")
            return false
        }
        return true
    }

    private fun handleLastError() {
        if (!myapp.haveinit) {
            Toast.makeText(this, AppConfig.Constr_connectfialed, Toast.LENGTH_SHORT).show()
            return
        }

        val errdata = ByteArray(255)
        val er = myapp.Mreader.ParamGet(
            Reader.Mtr_Param.MTR_PARAM_READER_ERRORDATA,
            errdata
        )

        if (myapp.ei.errstr == null) {
            myapp.Mreader.GetLastDetailError(myapp.ei)
        }

        val message = buildString {
            append("last:${myapp.ei.derrcode}")
            if (!myapp.ei.errstr.isNullOrEmpty()) {
                append(" ${myapp.ei.errstr}")
            }
            append(" errdata:${errdata[0]} ${errdata[1]}")
        }

        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
        myapp.ei.errstr = null
        myapp.ei.derrcode = 0
    }

    private fun registerBroadcastReceiver() {
        mBroadcastReceiver = MyBroadcastReceiver()
        registerReceiver(mBroadcastReceiver, IntentFilter().apply {
            addAction(Constants.BROADCAST_ACTION1)
            addAction(Constants.BROADCAST_ACTION2)
            addAction(Constants.BROADCAST_ACTION3)
            addAction(Intent.ACTION_BATTERY_CHANGED)
        })
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_BACK -> {
                handleBackPress()
                return true
            }
            139 -> {
                if (myapp.Rpower.GetType() == RfidPower.PDATYPE.CHAINWAY) {
                    handleChainwayKey()
                }
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun handleBackPress() {
        if (System.currentTimeMillis() - myapp.exittime > 2000) {
            Toast.makeText(this, AppConfig.Constr_Putandexit, Toast.LENGTH_SHORT).show()
            myapp.exittime = System.currentTimeMillis()
        } else {
            mViewModel.handler?.removeCallbacksAndMessages(null)
            myapp.Mreader?.let {
                it.CloseReader()
                myapp.needlisen = true
            }
            myapp.Rpower.PowerDown()
            finish()
        }
    }

    private fun handleChainwayKey() {
        if (button_read.isEnabled) {
            button_read.performClick()
        } else {
            button_stop.performClick()
        }
    }

    private fun handleError(error: String) {
        Toast.makeText(this, error, Toast.LENGTH_SHORT).show()
        tv_state.text = error
    }

    override fun onResume() {
        super.onResume()
        mViewModel.resumeReading()
    }

    override fun onPause() {
        super.onPause()
        mViewModel.pauseReading()
    }

    override fun onDestroy() {
        try {
            androidWakeLock.ReleaseWakeLock()
            unregisterReceiver(mBroadcastReceiver)
            screenListener.unregisterListener()

            if (myapp.isReport_rec) {
                myapp.fs?.close()
            }

            myapp.Mreader?.let {
                it.CloseReader()
                myapp.needlisen = true
            }

            myapp.Rpower?.PowerDown()

            soundPool.release()
        } catch (e: Exception) {
            Log.e("MainActivity", "Destroy error", e)
        } finally {
            exitProcess(0)
            super.onDestroy()
        }
    }

    // 设备连接处理
    private fun connectHandleUI() {
        try {
            setupReaderParameters()
            setupInventoryProtocols()
            setupAntennaPower()
            setupRegion()
            setupFrequency()
            setupGen2Parameters()
            setupTagFilter()
            setupEmbeddedData()
            updateModuleInfo()
        } catch (ex: Exception) {
            Log.e("MainActivity", "Connect handle error", ex)
            handleError("连接配置错误: ${ex.message}")
        }
    }

    private fun setupReaderParameters() {
        myapp.Rparams = myapp.spf.ReadReaderParams()
        if (myapp.Rparams.invpro.isEmpty()) {
            myapp.Rparams.invpro.add("GEN2")
        }
    }

    private fun setupInventoryProtocols() {
        val protocols = myapp.Rparams.invpro.mapNotNull { name ->
            when (name) {
                "GEN2" -> Reader.SL_TagProtocol.SL_TAG_PROTOCOL_GEN2
                "6B" -> Reader.SL_TagProtocol.SL_TAG_PROTOCOL_ISO180006B
                "IPX64" -> Reader.SL_TagProtocol.SL_TAG_PROTOCOL_IPX64
                "IPX256" -> Reader.SL_TagProtocol.SL_TAG_PROTOCOL_IPX256
                else -> null
            }
        }

        val ipst = myapp.Mreader.Inv_Potls_ST().apply {
            potlcnt = protocols.size
            potls = Array(potlcnt) { i ->
                myapp.Mreader.Inv_Potl().apply {
                    weight = 30
                    potl = protocols[i]
                }
            }
        }

        myapp.Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_INVPOTL, ipst)
    }

    private fun updateModuleInfo() {
        val moduleInfo = myapp.Mreader.HardwareDetails()
        val er = myapp.Mreader.GetHardwareDetails(moduleInfo)
        if (er == Reader.READER_ERR.MT_OK_ERR) {
            tv_module.text = moduleInfo.module.toString()
        }
    }

    private fun setupScreenListener() {
        screenListener = ScreenListener(this).apply {
            begin(object : ScreenListener.ScreenStateListener {
                override fun onScreenOn() {
                    // 屏幕点亮无需特殊处理
                }

                override fun onScreenOff() {
                    Log.d("MYINFO", "onScreenoff")
                    button_stop.takeIf { it.isEnabled }?.performClick()
                    myapp.Mreader?.let {
                        it.CloseReader()
                        myapp.needlisen = true
                    }
                    myapp.Rpower?.let {
                        it.PowerDown()
                        myapp.needreconnect = true
                    }
                }
            })
        }
    }

    private fun setupTabHostListener() {
        tabHost.setOnTabChangedListener { tabId ->
            val currentTab = tabHost.currentTab
            if (isRuleNoSelPt) {
                if (currentTab == 1) {
                    updateTagDataToSub3()
                }
            } else {
                if (currentTab == 2) {
                    updateTagDataToSub3()
                }
            }
        }
    }

    private fun updateTagDataToSub3() {
//        Sub3TabActivity.EditText_sub3fildata?.setText(myapp.Curepc)
//        Sub3TabActivity.EditText_sub3wdata?.setText(myapp.Curepc)
    }

    private fun handleDefaultPlatform() {
        if (isRuleNoSelPt) {
            myapp.Rpower = RfidPower(pdaType, applicationContext)

            val path = myapp.Rpower.GetDevPath()
            if (myapp.Rpower.PowerUp()) {
                val er = myapp.Mreader.InitReader_Notype(path, 1)
                myapp.antportc = 1
                myapp.Address = path

                val hwDetails = myapp.Mreader.HardwareDetails()
                val er2 = myapp.Mreader.GetHardwareDetails(hwDetails)
                myapp.myhd = hwDetails

                if (er == Reader.READER_ERR.MT_OK_ERR) {
                    connectHandleUI()
                }
            }
        }
    }

    private fun setupHeaderViews() {
        tv_once.text = "0"
        tv_tags.text = "0"
        tv_state.text = "..."
        tv_costt.text = "0"
        tv_timcost.text = "0"
        tv_statics.text = " 0/s,m:0/s"
    }

    private fun handleModeSet() {
        if (!mViewModel.selectInventoryMode()) {
            Toast.makeText(this, AppConfig.Constr_failed, Toast.LENGTH_SHORT).show()
        }
    }

    private fun setupAntennaPower() {
        val apcf = myapp.Mreader.AntPowerConf().apply {
            antcnt = myapp.antportc
            for (i in 0 until antcnt) {
                Powers[i] = myapp.Mreader.AntPower().apply {
                    antid = i + 1
                    readPower = myapp.Rparams.rpow[i].toShort()
                    writePower = myapp.Rparams.wpow[i].toShort()
                }
            }
        }

        myapp.Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_RF_ANTPOWER, apcf)
    }

    private fun setupRegion() {
        val region = when (myapp.Rparams.region) {
            0 -> Reader.Region_Conf.RG_PRC
            1 -> Reader.Region_Conf.RG_NA
            2 -> Reader.Region_Conf.RG_NONE
            3 -> Reader.Region_Conf.RG_KR
            4 -> Reader.Region_Conf.RG_EU
            else -> Reader.Region_Conf.RG_NONE
        }

        if (region != Reader.Region_Conf.RG_NONE) {
            myapp.Mreader.ParamSet(
                Reader.Mtr_Param.MTR_PARAM_FREQUENCY_REGION,
                region
            )
        }
    }

    private fun setupFrequency() {
        if (myapp.Rparams.frelen > 0) {
            val hdst = myapp.Mreader.HoptableData_ST().apply {
                lenhtb = myapp.Rparams.frelen
                htb = myapp.Rparams.frecys
            }
            myapp.Mreader.ParamSet(
                Reader.Mtr_Param.MTR_PARAM_FREQUENCY_HOPTABLE,
                hdst
            )
        }
    }

    private fun setupGen2Parameters() {
        with(myapp.Mreader) {
            // 设置Session
            ParamSet(
                Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_SESSION,
                intArrayOf(myapp.Rparams.session)
            )

            // 设置Q值
            ParamSet(
                Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_Q,
                intArrayOf(myapp.Rparams.qv)
            )

            // 设置写模式
            ParamSet(
                Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_WRITEMODE,
                intArrayOf(myapp.Rparams.wmode)
            )

            // 设置最大EPC长度
            ParamSet(
                Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_MAXEPCLEN,
                intArrayOf(myapp.Rparams.maxlen)
            )

            // 设置Target
            ParamSet(
                Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_TARGET,
                intArrayOf(myapp.Rparams.target)
            )
        }
    }

    private fun setupTagFilter() {
        if (myapp.Rparams.filenable == 1) {
            val tfst = myapp.Mreader.TagFilter_ST().apply {
                bank = myapp.Rparams.filbank
                val len = if (myapp.Rparams.fildata.length % 2 == 0) {
                    myapp.Rparams.fildata.length
                } else {
                    myapp.Rparams.fildata.length + 1
                }
                fdata = ByteArray(len / 2).also { data ->
                    myapp.Mreader.Str2Hex(
                        myapp.Rparams.fildata,
                        myapp.Rparams.fildata.length,
                        data
                    )
                }
                flen = myapp.Rparams.fildata.length * 4
                startaddr = myapp.Rparams.filadr
                isInvert = myapp.Rparams.filisinver
            }

            myapp.Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_FILTER, tfst)
        }
    }

    private fun setupEmbeddedData() {
        if (myapp.Rparams.emdenable == 1) {
            val edst = myapp.Mreader.EmbededData_ST().apply {
                accesspwd = null
                bank = myapp.Rparams.emdbank
                startaddr = myapp.Rparams.emdadr
                bytecnt = myapp.Rparams.emdbytec
            }

            myapp.Mreader.ParamSet(
                Reader.Mtr_Param.MTR_PARAM_TAG_EMBEDEDDATA,
                edst
            )
        }
    }


    companion object {
        private const val TAG = "MainActivity"
        lateinit var spinner_qmode: Spinner
    }
}